/*
 * Copyright 2017 Rainbow.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.seari.semodbus.server;

import com.ghgande.j2mod.modbus.net.AbstractModbusListener;
import com.ghgande.j2mod.modbus.net.ModbusListenerFactory;
import com.ghgande.j2mod.modbus.net.ModbusTCPListener;

/**
 *
 * @author Rainbow
 */
public class SEmodbusListenerFactory extends ModbusListenerFactory
{
    public static AbstractModbusListener createModbusListener(String address) throws Exception 
    {
        String parts[] = address.split(" *: *");
        if (parts.length < 2) {
            throw new IllegalArgumentException("missing connection information");
        }
        if (parts[0].toLowerCase().equals("tcp")) {
            // Create a ModbusTCPListener with the default interface
            // value.  The second optional value is the TCP port number
            ModbusTCPListener listener = new SEmodbusTCPListener(5);
            if (parts.length > 2) {
                int port = Integer.parseInt(parts[2]);
                listener.setPort(port);
            }
            Thread result = new Thread(listener);
            result.start();

            return listener;
        }else{
            throw new IllegalArgumentException("unknown type " + parts[0]);
        }
    }
}
